<template>
  <div class="login">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="name">
        <el-input type="username" v-model="ruleForm.name" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" id="login">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "login",
  data() {
    var validatename = (rule, value, callback) => {
      // let nameInfo = [];
      // JSON.parse(sessionStorage.getItem("accounts")).map((item, i) => {
      //   nameInfo.push(item.name);
      // });
      if (value === "") {
        callback(new Error("请输入用户名"));
      // } else if (nameInfo.indexOf(value) === -1) {
      //   callback(new Error("用户不存在"));
      } else {
        callback();
      }
    };
    var validatePass = async (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      // } else {
      //   var crypto = require("crypto");
      //   function cryp(word) {
      //     var md5 = crypto.createHash("md5");
      //     return md5.update(word).digest("hex");
      //   }
      //   this.$store.commit({
      //     type: "login",
      //     username: cryp(this.ruleForm.name),
      //     userpass: cryp(this.ruleForm.pass),
      //   });
      //   await this.getUserInfo();
      //   let code = JSON.parse(sessionStorage.getItem("code"));
      //   if (code !== 200) {
      //     callback(new Error("密码错误"));
        } else {
          callback();
        }
      // }
    };
    return {
      ruleForm: {
        name: "",
        pass: "",
      },
      rules: {
        name: [{ validator: validatename, trigger: "change" }],
        pass: [{ validator: validatePass, trigger: "change" }],
      },
    };
  },
  created() {
    //查询角色和权限信息
    this.$store.dispatch("getLogin");
  },
  mounted() {
    document.onkeydown = function (e) {
      var event = e || event;
      if (event.keyCode === 13) {
        let login = document.getElementById("login");
        login.click();
      }
    };
  },
  methods: {
    ...mapActions(["getUserInfo"]),
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //登录
          this.$store.commit({
            type: "login",
            username: this.ruleForm.name,
            userpass: this.ruleForm.pass,
          });
          await this.getUserInfo();
          let code = JSON.parse(sessionStorage.getItem("code"));
          if (code == 200) {
            // login user info
            let userMessage = JSON.parse(sessionStorage.getItem("userMessage"));
            // all role info
            let roles = JSON.parse(sessionStorage.getItem("roles"));
            // login user role_id
            let userRoleBits = [];
            // login user 权限
            let userRolePermissions = [];
            userRoleBits.push(userMessage.rolesId);
            userRolePermissions.push(userMessage.permissions);
            // roles.map((item,i) => {
            //   if(userMessage.rolesId == item.id) {
            //     userRoleBits.push(item.id);
            //     userRolePermissions.push(item.permissions);
            //   }
            // });
            sessionStorage.setItem("userRoleBits", JSON.stringify(userRoleBits));
            sessionStorage.setItem(
              "userRolePermissions",
              JSON.stringify(userRolePermissions)
            );
            // 用于当前用户密码修改
            sessionStorage.setItem(
            "oldPassword",
            JSON.stringify(this.ruleForm.pass)
            );
            //all permission info
            let permissions = JSON.parse(sessionStorage.getItem("permissions"));
            //get login user all permission_id?
            let permissionBits = [];
            permissions.map((item,i) => {
              for(let i = 0; i < userRolePermissions.length; i++) {
                if((item.id & userRolePermissions[i]) === item.id) {
                  permissionBits.push(item.id);
                }
              }
            });
            sessionStorage.setItem(
              "permissionBits",
              JSON.stringify(permissionBits)
            );
            this.$message({
              message: "恭喜，登录成功",
              type: "success",
            });
            this.$store.commit({
              type: "islogin",
              flag: true,
            });
            this.$router.push("entry");
            // if (sessionStorage.getItem("history_path")) {
            //   // 跳转审核后，清除历史
            //   this.$router.push(sessionStorage.getItem("history_path"));
            //   sessionStorage.removeItem("history_path");
            // } else {
            //   this.$router.push("entry");
            // }
          } else {
            this.$message({
              message: "抱歉，登录失败",
              type: "warning",
            });
          }
        } else {
          this.$message({
            message: "抱歉，登录失败",
            type: "warning",
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },

}
</script>
<style scoped>
.el-form {
  width: 350px;
  margin: auto;
}
.login {
  position: absolute;
  left: 38%;
  top: 35%;
}
</style>